package org.montecristo.posmobile.previo;

public class ExpressionBuilder {

	public static String process(String input){
		String expression = "";		
		int count;
		char tokn = 0;
		count = 0;
	
		for(int cursor=0;cursor<input.length();cursor++){
			
			if(tokn==0){
			tokn = input.charAt(cursor);
			count++;}
			else if(tokn==input.charAt(cursor))
				count++;
			else{
				expression = expression.concat(getRegEx(tokn,count));
				tokn=input.charAt(cursor);
				count=1;
			}			
			if(cursor+1>=input.length()){
				expression = expression.concat(getRegEx(tokn,count));				
			}
			
			if(tokn=='\\'&&cursor+1<input.length()){
				cursor++;
				tokn = input.charAt(cursor);
				if(tokn!='A'&&tokn!='L'&&tokn!='N'&&tokn!='I'){
				expression+=getSpecialCharRegEx(tokn);}				
				tokn=0;
				count=0;
			}
			
		}		
		
		return expression;
	}
	
	private static String getSpecialCharRegEx(char s){
		if(s=='\\')return "[\\\\]{1}";
		return "["+s+"]{1}";
	}
	
	private static String getRegEx(char c,int count){
		String r;
		switch(c){
		case 'A': 
			r=("[A-Za-z0-9]"+"{"+count+"}");
			break;
		case 'L': 
			r=("[A-Z,a-z]"+"{"+count+"}");
			break;
		case 'N': 
			r=("[0-9]"+"{"+count+"}");
			break;
		case 'I': 
			r=("[a-z]"+"{"+count+"}");
			break;
		default: r="ERROR"; break;
		}
		return r;
	}
}
